//
//  LYBtnLabel.m
//  SZBank
//
//  Created by LuoYao on 16/7/13.
//  Copyright © 2016年 LuoYao. All rights reserved.
//

#import "LYBtnLabel.h"

@interface LYBtnLabel ()
{
    CGFloat _width,_height;
    UIButton *lastBtn;/**< 最后选中的Btn */
    NSString *_nameId;/**< 题目Id */
    NSArray *dataSource;
}
@end
@implementation LYBtnLabel

- (instancetype)initWithFrame:(CGRect)frame array:(NSArray *)array nameId:(NSString *)nameId
{
    self = [super initWithFrame:frame];
    if (self) {
        _width = frame.size.width;
        _height = frame.size.height;
        
        _nameId = nameId;
        dataSource = array;

        for (int i = 0; i < array.count; i ++) {
            
               UIView *view = [self imageAndLabelViewWithFrame:CGRectMake(0, i * 50, _cKwidth * 0.8, 50) contentText:[NSString stringWithFormat:@"%@.%@",array[i][@"optionvalue"],array[i][@"optionname"]] btnTag:i];
            [self addSubview:view];
            
        }
        
    }
    return self;
}




#pragma mark - 点击事件
- (void)action_BtnClick:(UIButton *)sender{
    //改变选中状态
    sender.selected = !sender.selected;
    
    //获取当前选中的内容
    NSString *string;

    if (sender.selected) {
        string = dataSource[sender.tag - 1000][@"optionvalue"];
    }else{
        string = @"NoSelected";
    }
    
    //上一个按钮置为未选中状态
    if (sender.tag != lastBtn.tag) {
        lastBtn.selected = NO;
    }
    
    lastBtn = sender;
    
    //代理赋值
    NSDictionary *dic = [NSDictionary dictionary];
    dic = @{_nameId:string,@"nameId":_nameId,@"string":string};
    
    if (self.delegate) {
        [self.delegate btnLabel:self inputDictionary:dic];
    }
}


#pragma mark - 自定义方法
- (UIView *)imageAndLabelViewWithFrame:(CGRect)frame contentText:(NSString *)contentText btnTag:(NSInteger)btnTag{
    
    UIView *view = [[UIView alloc] initWithFrame:frame];
    
    UIButton *btn = [[UIButton alloc] initWithFrame:CGRectMake(_cKwidth * 0.8 * 0.04, (frame.size.height - 27) / 2, 27, 27)];
    btn.tag = 1000 + btnTag;
    [btn setImage:[LocalDataManager getImageWithSourceOfPath:@"未选中"] forState:UIControlStateNormal];
    [btn setImage:[LocalDataManager getImageWithSourceOfPath:@"选中"] forState:UIControlStateSelected];
    
    [btn addTarget:self action:@selector(action_BtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UILabel *lb = [[UILabel alloc] initWithFrame:CGRectMake(_cKwidth * 0.8 * 0.1, 0, _cKwidth * 0.7, 50)];
    lb.text = contentText;
    lb.font = [UIFont systemFontOfSize:FONT_SIZE];
    
    
    [view addSubview:btn];
    [view addSubview:lb];
    
    return view;
    
}

@end
